package com.example.demo.service;

import com.csvreader.CsvWriter;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;

/**
 * @author luoyong
 * @since 1.1-baseline
 */
@Service
public class CvsService {

    public void writeAndDownLoad(HttpServletResponse response, String fileName) {

        try {
            File file = File.createTempFile("xxx", ".csv");
            CsvWriter csvWriter = new CsvWriter(file.getCanonicalPath(), ',', Charset.forName("UTF-8"));
            String[] heads = {"a","b","c"};
            String[] content = {"1","2","3"};
            csvWriter.writeRecord(heads,true);
            csvWriter.writeRecord(content,true);
            csvWriter.writeRecord(content,true);
//            csvWriter.writeRecord(new String[]{"value1", "value2","1","3","2"});
//            csvWriter.writeRecord(new String[]{"value1", "value2","1","3","2"});
//            csvWriter.writeRecord(new String[]{"value1", "value2"});
            csvWriter.close();

            response.setContentType("application/csv; charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            InputStream in = new FileInputStream(file);
            OutputStream out = response.getOutputStream();
            int len;
            byte[] buffer = new byte[1024];
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
